#!/usr/bin/env bash
#
# Summary: Set or show the local application-specific Node version
#
# Usage: nodenv local <version>
#        nodenv local --unset
#
# Sets the local application-specific Node version by writing the
# version name to a file named `.node-version'.
#
# When you run a Node command, nodenv will look for a `.node-version'
# file in the current directory and each parent directory. If no such
# file is found in the tree, nodenv will use the global Node version
# specified with `nodenv global'. A version specified with the
# `NODENV_VERSION' environment variable takes precedence over local
# and global versions.
#
# For backwards compatibility, nodenv will also read version
# specifications from `.nodenv-version' files, but a `.node-version'
# file in the same directory takes precedence.
#
# <version> should be a string matching a Node version known to nodenv.
# The special version string `system' will use your default system Node.
# Run `nodenv versions' for a list of available Node versions.

set -e
[ -n "$NODENV_DEBUG" ] && set -x

# Provide nodenv completions
if [ "$1" = "--complete" ]; then
  echo --unset
  echo system
  exec nodenv-versions --bare
fi

NODENV_VERSION="$1"

if [ "$NODENV_VERSION" = "--unset" ]; then
  rm -f .node-version .nodenv-version
elif [ -n "$NODENV_VERSION" ]; then
  previous_file="$(NODENV_VERSION= nodenv-version-origin || true)"
  nodenv-version-file-write .node-version "$NODENV_VERSION"
  if [ "$previous_file" -ef .nodenv-version ]; then
    rm -f .nodenv-version
    { echo "nodenv: removed existing \`.nodenv-version' file and migrated"
      echo "       local version specification to \`.node-version' file"
    } >&2
  fi
else
  nodenv-version-file-read .node-version ||
  nodenv-version-file-read .nodenv-version ||
  { echo "nodenv: no local version configured for this directory"
    exit 1
  } >&2
fi
